using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.Text.RegularExpressions;

namespace c3o.Framework.Web
{
    public class RssReader 
    {
        public DataTable Header = null;
        public DataTable Detail = null;
		private SiteReader sr;
		public string TorrentPath = "Torrents";

		public RssReader(string url)
		{
			this.LoadData(url, null, null);

			//SiteReader sr = new SiteReader();
			//XmlDocument xml = new XmlDocument();

			//// Read rss feed into XmlDocument
			//xml.LoadXml(sr.ReadPage(url));

			//this.LoadData(xml);			
		}

		public RssReader(string url, string pattern, string replacement)
		{
			this.sr = new SiteReader();

			this.LoadData(url, pattern, replacement);
		}
		

		public RssReader(XmlDocument xml)
        {
			this.sr = new SiteReader();

			this.LoadData(xml);

            //XmlDocument xml = new XmlDocument();

            // Read rss feed into XmlDocument
      //      xml.LoadXml(this.ReadPage(url));

			//// Load header into datatable
			//this.Header = this.GetRssHeader(xml);

			//// Load items into datatable
			//this.Detail = this.GetRssItems(xml);
			
        }


		public void LoadData(string url, string pattern, string replacement)
		{			
			XmlDocument xml = new XmlDocument();

			// Read rss feed into XmlDocument
			string xmlstring = this.sr.ReadPage(url);

			if (pattern != null && pattern.Length > 0 && replacement != null && replacement.Length > 0)
			{
				Regex reg = new Regex(pattern);
				xmlstring = reg.Replace(xmlstring, replacement);
			}

			xml.LoadXml(xmlstring);

			this.LoadData(xml);
		}


		public void LoadData(XmlDocument xml)
		{
			// Load header into datatable
			this.Header = this.GetRssHeader(xml);

			// Load items into datatable
			this.Detail = this.GetRssItems(xml);
		}




		public void DownloadTorrent(string url)
		{
			int i = 1;
			if (url != null && url.Length > 0)
			{
				if (!System.IO.Directory.Exists(this.TorrentPath)) System.IO.Directory.CreateDirectory(this.TorrentPath);

				// Find file name
				string FileName = this.TorrentPath + @"\temp" + i.ToString() + ".torrent";
				while (System.IO.File.Exists(FileName))
				{
					i++;
					FileName = this.TorrentPath + @"\temp" + i.ToString() + ".torrent";
				}

				// Save Torrent file to disk
				this.sr.Download(url, FileName);

				// Launch client
				System.Diagnostics.Process.Start(FileName);
			}
		}


        public DataTable GetRssHeader(XmlDocument xml)
        {
            DataTable dt = null;

            XmlElement nodRoot = xml.DocumentElement;
            XmlNodeList nodItems = nodRoot.GetElementsByTagName("channel");

            foreach (XmlElement item in nodItems)
            {
                //XmlAttributeCollection itemAttributes = item.Attributes;
                XmlNodeList itemChildren = item.ChildNodes;

                // Create datatable
                if (dt == null)
                {
                    dt = new DataTable();

                    foreach (XmlNode childNode in itemChildren)
                    {
                        if (childNode.Name != "item"  &&
                            childNode.Name != "itunes:category" ) 
                        {
							if (!dt.Columns.Contains(childNode.Name))
							{
								dt.Columns.Add(childNode.Name);

								foreach (XmlAttribute attribute in childNode.Attributes)
								{
									if (!dt.Columns.Contains(childNode.Name + "_" + attribute.Name))
									{
										dt.Columns.Add(childNode.Name + "_" + attribute.Name);
									}
								}
							}
                        }
                    }
                }

                DataRow row = dt.NewRow();

                // Populate columns in row
                foreach (XmlNode childNode in itemChildren)
                {
                    if (childNode.Name != "item" &&
                        childNode.Name != "itunes:category")
                    {
                        row[childNode.Name] = childNode.InnerXml;                        

                        foreach (XmlAttribute attribute in childNode.Attributes)
                        {
							switch(attribute.NodeType)
							{
								case XmlNodeType.CDATA:
									break;
								default:
									row[childNode.Name + "_" + attribute.Name] = attribute.Value;
									break;
							}
                        }
                    }
                }

                dt.Rows.Add(row);
            }

            //	return availTorrents;
            return dt;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public DataTable GetRssItems(XmlDocument xml)
        {
            DataTable dt = new DataTable();

            XmlElement nodRoot = xml.DocumentElement;
            XmlNodeList nodItems = nodRoot.GetElementsByTagName("item");

            foreach (XmlElement item in nodItems)
            {
                XmlAttributeCollection itemAttributes = item.Attributes;
                XmlNodeList itemChildren = item.ChildNodes;

                // Create columns as needed
                foreach (XmlNode childNode in itemChildren)
                {
                    if (!dt.Columns.Contains(childNode.Name))
                    {
                        dt.Columns.Add(childNode.Name);

                        foreach (XmlAttribute attribute in childNode.Attributes)
                        {
                            if (!dt.Columns.Contains(childNode.Name + "_" + attribute.Name))
                            {
                                dt.Columns.Add(childNode.Name + "_" + attribute.Name);
                            }
                        }
                    }
                }

                // Get Row to hold data
                DataRow row = dt.NewRow();

                // Populate columns in row
                foreach (XmlNode childNode in itemChildren)
                {
					//row[childNode.Name] = childNode.InnerXml;
					row[childNode.Name] = childNode.InnerText;


                    foreach (XmlAttribute attribute in childNode.Attributes)
                    {
						row[childNode.Name + "_" + attribute.Name] = attribute.Value;

						//switch (attribute.NodeType)
						//{
						//    case XmlNodeType.CDATA:
						//        int i = 0;
						//        break;
						//    default:
						//        row[childNode.Name + "_" + attribute.Name] = attribute.Value;
						//        break;
						//}

					}
                }

                dt.Rows.Add(row);
            }

            //	return availTorrents;
            return dt;
        }
    }
}